package is.billsharing.app;

/**
 * @author Anusha
 *
 */

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BillsharingappActivity extends Activity {
	protected static final String PREFS_NAME = "user";
	EditText un, pw;
	Button ok, reg;
	int uid;
	String uname;
	TextView tv_error;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		un = (EditText) findViewById(R.id.et_un);
		pw = (EditText) findViewById(R.id.et_pw);
		ok = (Button) findViewById(R.id.btn_login);
		reg = (Button) findViewById(R.id.button2);
		tv_error = (TextView) findViewById(R.id.error);

		ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
				postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));

				String response = null;
				try {
					response = CustomHttpClient.executeHttpPost("AndroidResponse",postParameters);
					String res = response.toString();
					res = res.replaceAll("\\s+", "");
					if (res.equals("false1")) {
						tv_error.setText("invalid username or password");
						un.setText("");
						pw.setText("");
					} else {

						JSONObject json = new JSONObject(res);
						uid = Integer.parseInt(json.getString("uid"));
						uname = json.getString("uname");
						tv_error.setText(uname);
						SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
						SharedPreferences.Editor editor = settings.edit();
						editor.putInt("uid", uid);
						editor.putString("uname", uname);
						editor.commit();
						Intent intent = new Intent(BillsharingappActivity.this,TabsampleActivity.class);
						startActivity(intent);					
					}

				} catch (Exception e) {

				}

			}
		});

		reg.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(BillsharingappActivity.this,RegisterActivity.class);
				startActivity(intent);

			}
		});
	}
}